package topcbl.task;

import topcbl.net.TaxiService;
import topcbl.taxi.MainActivity;
import topcbl.taxi.R;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.Intent;
import android.os.AsyncTask;
import android.widget.Toast;

public class SignInTask extends AsyncTask<Void, String, Void> {
	Context context;
	final ProgressDialog pDialog;
	TaxiService mService;
	String acc, pass;

	public SignInTask(Context context, String acc, String pass) {
		this.context = context;
		pDialog = ProgressDialog.show(context,
				context.getString(R.string.navigation_item_change1),
				context.getString(R.string.progress_connect));
		mService = MainActivity.mBindService.getService();
		this.acc = acc;
		this.pass = pass;
	}

	@Override
	protected void onPreExecute() {
		super.onPreExecute();
		// show progress dialog
		pDialog.setCanceledOnTouchOutside(true);
		pDialog.setCancelable(true);
		pDialog.setOnCancelListener(new OnCancelListener() {

			@Override
			public void onCancel(DialogInterface dialog) {
				cancel(true);
			}
		});
	}

	@Override
	protected Void doInBackground(Void... params) {
		if (!mService.isConnect2Server()) {
			publishProgress("LOST_CONNECTION");
			return null;
		}
		if (mService.login(acc, pass)) {
			Intent move2Main = new Intent(context, MainActivity.class);
			context.startActivity(move2Main);
		} else {
			publishProgress("WRONG_PASS");
		}
		return null;
	}

	@Override
	protected void onProgressUpdate(String... values) {
		super.onProgressUpdate(values);
		switch (values[0]) {
		case "WRONG_PASS":
			Toast.makeText(
					context,
					context.getResources().getString(
							R.string.splash_text_wrong_acc_pass),
					Toast.LENGTH_SHORT).show();
			break;
		case "LOST_CONNECTION":
			Toast.makeText(
					context,
					context.getResources().getString(
							R.string.splash_text_fail_connect),
					Toast.LENGTH_SHORT).show();
			break;
		}

	}

	@Override
	protected void onPostExecute(Void result) {
		pDialog.dismiss();
		super.onPostExecute(result);
	}

	@Override
	protected void onCancelled() {
		pDialog.dismiss();
		super.onCancelled();
	}
}
